<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起人id" prop="initiatorId">
        <el-input
          v-model="queryParams.initiatorId"
          placeholder="请输入发起人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核人id" prop="approverId">
        <el-input
          v-model="queryParams.approverId"
          placeholder="请输入审核人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:research:add']"
        >新增</el-button>
      </el-col>
   <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:research:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:research:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:research:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="researchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="projectCode" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目类别" align="center" prop="catoryType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zsw_research_type" :value="scope.row.categoryType"/>
        </template>
      </el-table-column>
      <el-table-column label="发起人id" align="center" prop="initiatorId" />
      <el-table-column label="立项日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目目标" align="center" prop="goal" />
      <el-table-column label="项目描述" align="center" prop="description" />
      <el-table-column label="预计预算" align="center" prop="budget" />
      <el-table-column label="预期成果" align="center" prop="expectedOutcome" />
      <el-table-column label="状态" align="center" prop="approvalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zsw_build_status" :value="scope.row.approvalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人id" align="center" prop="approverId"/>
      <el-table-column label="审核意见或备注" align="center" prop="approvalComments" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:research:edit']"
            v-show="scope.row.initiatorId==scope.row.correntUid&&scope.row.approvalStatus==3||scope.row.correntUid==1"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleCheck(scope.row)"
            v-hasPermi="['zsw_project_check']"
            v-show="scope.row.approvalStatus==1||scope.row.approvalStatus==1&&scope.row.correntUid==1"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top-right"
            @click="handleDelete(scope.row)"
            v-show="scope.row.initiatorId==scope.row.correntUid&&scope.row.approvalStatus==2||scope.row.approvalStatus==2&&scope.row.correntUid==1"
          >申报</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:research:remove']"
            v-show="scope.row.initiatorId==scope.row.correntUid&&scope.row.approvalStatus==3||scope.row.correntUid==1"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-date"
            @click="handleTrack(scope.row)"
          >历史</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改科研项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编号" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="项目类别" prop="categoryType">
          <el-radio-group v-model="form.categoryType" >
            <el-radio
              v-for="dict in dict.type.zsw_research_type"
              :key="dict.value"
              :label="dict.value"
              :disabled="docheck"
            >{{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发起人id" prop="initiatorId">
          <el-input v-model="form.initiatorId" placeholder="请输入发起人id" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="立项日期" prop="startDate" >
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择立项日期" v-bind:readonly="docheck">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目目标" prop="goal" >
          <el-input v-model="form.goal" placeholder="请输入项目目标" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入项目描述" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="预计预算" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入预计预算" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="预期成果" prop="expectedOutcome">
          <el-input v-model="form.expectedOutcome" placeholder="请输入预期成果" v-bind:readonly="docheck"/>
        </el-form-item>
        <el-form-item label="审核人id" prop="approverId" v-show="onlyconfirmer">
          <el-input v-model="form.approverId" placeholder="请输入审核人id"/>
        </el-form-item>
        <el-form-item label="是否通过" prop="confirmresult" v-show="onlyconfirmer">
              <el-radio-group v-model="form.confirmresult">
                <el-radio
                  v-for="dict in dict.type.zsw_confirm_result"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见或备注" prop="approvalComments" v-show="onlyconfirmer">
          <el-input v-model="form.approvalComments" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>     
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 历史操作数据对话框 -->
    <el-dialog :title="title" :visible.sync="track" width="80%"  append-to-body>
    <el-table  :data="trackList" height="400px">
      <el-table-column label="项目编号" align="center" prop="projectCode" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目类别" align="center" prop="catoryType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zsw_research_type" :value="scope.row.categoryType"/>
        </template>
      </el-table-column>
      <el-table-column label="发起人id" align="center" prop="initiatorId" />
      <el-table-column label="立项日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目目标" align="center" prop="goal" />
      <el-table-column label="项目描述" align="center" prop="description" />
      <el-table-column label="预计预算" align="center" prop="budget" />
      <el-table-column label="预期成果" align="center" prop="expectedOutcome" />
      <el-table-column label="状态" align="center" prop="approvalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zsw_build_status" :value="scope.row.approvalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人id" align="center" prop="approverId"/>
      <el-table-column label="审核意见或备注" align="center" prop="approvalComments" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button
            size="mini"
            type="danger"
            icon="el-icon-refresh-left"
            @click="handleTrackBack(scope.row)"
        >溯回</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="doconfirm" width="500px" append-to-body>
      <el-form ref="form" :model="form"  label-width="80px">
        <el-form-item label="绑定邮箱" prop="clockedemail">
          <el-input v-model="form.clockedemail" v-bind:readonly="true"/>
        </el-form-item> 
        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="form.verificationCode" style="width: 70%"/>
          <el-button  
            type="primary" 
            :disabled="isSending" 
            @click="handleSend" 
            style="width: 25%;position: absolute;right: 0;margin-right: 5px;text-align:center;"
            >{{ buttonText }}</el-button>
        </el-form-item>
      </el-form>     
      <div slot="footer" class="dialog-footer" >
      <el-button type="primary" @click="handleverify">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listResearch, getResearch, delResearch, addResearch, updateResearch, getTracklist, TrackBack, sendVerificationCode,verifyVerificationCode} from "@/api/project/research";
import axios from "axios";
export default {
  name: "Research",
  dicts: ['zsw_research_type','zsw_build_status','zsw_confirm_result'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研项目表格数据
      researchList: [],
      // 操作历史表格数据
      trackList: [],
      track: false,
      //验证对话框显示
      doconfirm: false,
      // 倒计时秒数
      countdown: 0,
      //验证码文本
      buttonText: '发送验证码',     
      // 控制按钮是否禁用  
      isSending: false,   
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //锁定输入框
      docheck: false,
      //修改与审批切换
      exchange: true,
      //仅对审批人显示
      onlyconfirmer: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        categoryType: null,
        initiatorId: null,
        startDate: null,
        goal: null,
        description: null,
        budget: null,
        expectedOutcome: null,
        approvalStatus: null,
        projectCode: null,
        approverId: null,
        approvalComments: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null,
        deletedBy: null,
        deletedAt: null,
        isDeleted: null,
        version: null,
        correntUid: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        categoryType: [
          { required: true, message: "项目类别不能为空", trigger: "change" }
        ],
        initiatorId: [
          { required: true, message: "发起人id不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "项目立项日期不能为空", trigger: "blur" }
        ],
        projectCode: [
          { required: true, message: "项目编号不能为空", trigger: "blur" }
        ],
        createdBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        confirmresult: [],
        approvalComments: [],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询科研项目列表 */
    getList() {
      this.loading = true;
      listResearch(this.queryParams).then(response => {
        this.researchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        categoryType: null,
        initiatorId: null,
        startDate: null,
        goal: null,
        description: null,
        budget: null,
        expectedOutcome: null,
        approvalStatus: null,
        projectCode: null,
        approverId: null,
        approvalComments: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null,
        deletedBy: null,
        deletedAt: null,
        isDeleted: null,
        version: null,
        correntUid: null,
        confirmresult: null,
        clockedemail: null,
        verificationCode: null
      };
      this.resetForm("form");
      this.docheck=false;
      this.doconfirm=false;
      this.exchange=true;
      this.onlyconfirmer=false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科研项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      getResearch(projectId).then(response => {
        this.form = response.data;
        this.doconfirm = true;
        this.title = "验证身份"
})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            if(this.form.confirmresult==1){
              this.form.approvalStatus="2";
              updateResearch(this.form).then(response => {
              this.$modal.msgSuccess("审批成功");
              this.open = false;
              this.getList();
              });
            }else if(this.form.confirmresult==0){
              this.form.approvalStatus="3";
              updateResearch(this.form).then(response => {
              this.$modal.msgSuccess("审批成功");
              this.open = false;
              this.getList();
              });
            }else{
              this.form.approvalStatus="1";
              this.form.approvalComments="";
              updateResearch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });}
          } else {
            addResearch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除科研项目编号为"' + projectIds + '"的数据项？').then(function() {
        return delResearch(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/research/export', {
        ...this.queryParams
      }, `research_${new Date().getTime()}.xlsx`)
    },
    /** 审批按钮操作 */
    handleCheck(row) {
      this.reset();
      this.rules.confirmresult=[{ required: true, message: "选项为必选项", trigger: "blur" }];
      this.rules.approvalComments=[{ required: true, message: "审核意见不能为空", trigger: "blur" }];
      const projectId = row.projectId || this.ids
      getResearch(projectId).then(response => {
        this.form = response.data;
        this.exchange= false;
        this.onlyconfirmer= true;
        this.open = true;
        if(this.form.approvalStatus=="1"){
          this.docheck= true;
        }
        this.title = "审批科研项目";
      });
    },
    /** 历史按钮操作 */
    handleTrack(row) {
      console.log(row);
      getTracklist(row.projectId).then(response => {
        this.trackList = response.rows;
        this.title="历史操作数据"
        this.track=true;
      })
    },
    /** 数据回溯 */
    handleTrackBack(row){
      console.log(row);
      TrackBack(row).then(response => {
        this.$modal.msgSuccess("回溯成功");
        this.track=false;
        this.getList();
      })
    },
    /** 发送验证码 */
    handleSend() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          sendVerificationCode().then(response => {
              if (response.code===200) {
                this.$message.success('验证码已发送');
                this.startCountdown();
              } else {
                this.$message.error('验证码发送失败，请稍后重试');
              }
            })
            .catch(error => {
              this.$message.error('验证码发送失败，请稍后重试');
              console.error(error);
            });
        } else {
          this.$message.warning('请填写正确的邮箱地址');
        }
      });
    },
    //倒计时秒数
    startCountdown() {
      this.countdown = 60;
      this.isSending = true;
      const interval = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(interval);
          this.isSending = false;
          this.buttonText = '发送验证码';
        } else {
          this.countdown--;
          this.buttonText = `${this.countdown}秒后重试`;
        }
      }, 1000);
    },
    //验证验证码
    handleverify(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          verifyVerificationCode(this.form.verificationCode).then(response => {
              console.log(response);
              if(response.data.body==true){
                this.$message.success('验证身份成功');
                this.doconfirm=false;
                this.open=true;
                this.title="修改科研项目";
              }else if(response.data.body==false){
                this.$message.error('验证码不正确,请重试');
                this.form.verificationCode='';
              }else{
                this.$message.warning('验证码已失效,请重新获取')
                this.form.verificationCode='';
              }
          })
        }
      })
    }
  }
};
</script>
